<template>
  <div class="profile-container">
    <!-- 页面头部 -->
    <div class="profile-header">
      <div class="header-bg"></div>
      <div class="header-content">
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <img 
              :src="userInfo.userAvatar || defaultAvatar" 
              :alt="userInfo.userName"
              class="user-avatar"
            />
            <div class="avatar-overlay" @click="showAvatarUpload = true">
              <el-icon><Camera /></el-icon>
            </div>
          </div>
          <div class="user-basic-info">
            <h2 class="username">{{ userInfo.userName || '未设置用户名' }}</h2>
            <p class="user-role">{{ getRoleText(userInfo.userRole) }}</p>
            <p class="join-time">加入时间：{{ formatDate(userInfo.createTime) }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 个人信息卡片 -->
    <div class="profile-content">
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><User /></el-icon>
              个人信息
            </span>
            <el-button 
              type="primary" 
              :icon="Edit" 
              @click="toggleEditMode"
              :loading="loading"
            >
              {{ isEditing ? '保存' : '编辑' }}
            </el-button>
          </div>
        </template>

        <el-form 
          ref="profileFormRef"
          :model="editForm" 
          :rules="formRules"
          label-width="120px"
          class="profile-form"
        >
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="用户ID" prop="id">
                <el-input v-model="editForm.id" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户名" prop="userName">
                <el-input 
                  v-model="editForm.userName" 
                  :disabled="!isEditing"
                  placeholder="请输入用户名"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="用户角色" prop="userRole">
                <el-select 
                  v-model="editForm.userRole" 
                  :disabled="!isEditing"
                  placeholder="请选择角色"
                  style="width: 100%"
                >
                  <el-option label="普通用户" value="user" />
                  <el-option label="管理员" value="admin" />
                  <el-option label="超级管理员" value="super_admin" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最后更新" prop="updateTime">
                <el-input v-model="displayUpdateTime" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="个人简介" prop="userProfile">
            <el-input
              v-model="editForm.userProfile"
              :disabled="!isEditing"
              type="textarea"
              :rows="4"
              placeholder="请输入个人简介"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 统计信息卡片 -->
      <el-card class="stats-card" shadow="hover">
        <template #header>
          <span class="card-title">
            <el-icon><DataAnalysis /></el-icon>
            账户统计
          </span>
        </template>
        <el-row :gutter="24" class="stats-row">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number">{{ userInfo.id ? '1' : '0' }}</div>
              <div class="stat-label">账户数量</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number">{{ getDaysFromCreate() }}</div>
              <div class="stat-label">使用天数</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number">{{ userInfo.userRole === 'admin' ? '管理员' : '用户' }}</div>
              <div class="stat-label">当前身份</div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="showAvatarUpload"
      title="更换头像"
      width="400px"
      center
    >
      <div class="avatar-upload-content">
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="handleAvatarUpload"
        >
          <img v-if="previewAvatar" :src="previewAvatar" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <p class="upload-tip">支持 JPG、PNG 格式，文件大小不超过 2MB</p>
      </div>
      <template #footer>
        <el-button @click="showAvatarUpload = false">取消</el-button>
        <el-button type="primary" @click="confirmAvatarUpload">确认上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Edit, Camera, Plus, DataAnalysis } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useUserStore } from '@/stores/user'

// 使用用户store
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const isEditing = ref(false)
const showAvatarUpload = ref(false)
const previewAvatar = ref('')
const profileFormRef = ref(null)

// 用户信息直接从store获取
const userInfo = computed(() => userStore.userInfo)

// 编辑表单
const editForm = reactive({
  id: '',
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: 'user',
  updateTime: ''
})

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 表单验证规则
const formRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  userProfile: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
  ]
}

// 计算属性
const displayUpdateTime = computed(() => {
  return formatDate(editForm.updateTime)
})

// 获取用户信息
const getUserInfo = async () => {
  loading.value = true
  try {
    // 如果store中已有用户信息，直接使用
    if (userStore.userInfo.id) {
      // 同步到编辑表单
      Object.assign(editForm, userStore.userInfo)
      loading.value = false
      return
    }
    
    // 如果store中没有用户信息，从API获取
    await userStore.fetchUserInfo()
    // 同步到编辑表单
    Object.assign(editForm, userStore.userInfo)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 切换编辑模式
const toggleEditMode = async () => {
  if (isEditing.value) {
    // 保存模式
    await saveUserInfo()
  } else {
    // 编辑模式
    isEditing.value = true
  }
}

// 保存用户信息
const saveUserInfo = async () => {
  if (!profileFormRef.value) return
  
  try {
    const valid = await profileFormRef.value.validate()
    if (!valid) return

    loading.value = true
    
    // 使用store更新用户信息
    await userStore.updateUserInfo(editForm)
    
    isEditing.value = false
    ElMessage.success('保存成功！')
    
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  
  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    previewAvatar.value = e.target.result
  }
  reader.readAsDataURL(file)
  
  return false // 阻止自动上传
}

// 处理头像上传
const handleAvatarUpload = () => {
  // 这里处理自定义上传逻辑
}

// 确认头像上传
const confirmAvatarUpload = () => {
  if (previewAvatar.value) {
    editForm.userAvatar = previewAvatar.value
    userInfo.value.userAvatar = previewAvatar.value
    showAvatarUpload.value = false
    ElMessage.success('头像更新成功！')
  }
}

// 工具函数
const getRoleText = (role) => {
  const roleMap = {
    'user': '普通用户',
    'admin': '管理员',
    'super_admin': '超级管理员'
  }
  return roleMap[role] || '未知角色'
}

const formatDate = (dateString) => {
  if (!dateString) return '未设置'
  return new Date(dateString).toLocaleString('zh-CN')
}

const getDaysFromCreate = () => {
  if (!userInfo.value.createTime) return 0
  const createDate = new Date(userInfo.value.createTime)
  const now = new Date()
  const diffTime = Math.abs(now - createDate)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays
}

// 生命周期
onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.profile-header {
  position: relative;
  margin-bottom: 30px;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 200px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  opacity: 0.8;
}

.header-content {
  position: relative;
  z-index: 2;
  padding: 40px;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 30px;
}

.avatar-wrapper {
  position: relative;
}

.user-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 4px solid rgba(255, 255, 255, 0.3);
  object-fit: cover;
  transition: all 0.3s ease;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  cursor: pointer;
  transition: opacity 0.3s ease;
  color: white;
  font-size: 24px;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.user-basic-info {
  color: white;
}

.username {
  font-size: 32px;
  font-weight: bold;
  margin: 0 0 10px 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.user-role {
  font-size: 18px;
  margin: 0 0 8px 0;
  opacity: 0.9;
}

.join-time {
  font-size: 14px;
  margin: 0;
  opacity: 0.8;
}

.profile-content {
  display: grid;
  gap: 30px;
  grid-template-columns: 2fr 1fr;
}

.info-card, .stats-card {
  border-radius: 20px;
  border: none;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.profile-form {
  margin-top: 20px;
}

.stats-row {
  margin-top: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 15px;
  color: white;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.avatar-upload-content {
  text-align: center;
}

.avatar-uploader {
  display: inline-block;
}

.avatar-uploader :deep(.el-upload) {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar-preview {
  width: 178px;
  height: 178px;
  object-fit: cover;
}

.upload-tip {
  margin-top: 15px;
  color: #999;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-content {
    grid-template-columns: 1fr;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
    gap: 20px;
  }
  
  .username {
    font-size: 24px;
  }
}
</style>